package dao

import (
	"fmt"
	"lib/structs/ams"
	"lib/structs/tables"
	"time"
)

var ClientDao = new(clientDao)

type clientDao struct{}

func (d clientDao) List() (li []tables.AmsClient, err error) {
	err = DB.Find(&li).Error
	return
}
func (d clientDao) FindPage(in ams.SearchClientPage) (li []tables.AmsClient, total int64, err error) {
	tx := DB.Model(&tables.AmsClient{})
	tx.Where(" hostname like ? ", fmt.Sprintf("%%%s%%", in.Hostname))
	tx.Where(" ip like ? ", fmt.Sprintf("%%%s%%", in.Ip))
	tx.Count(&total).Offset((in.PageNum - 1) * in.PageSize).Limit(in.PageSize).Find(&li)
	err = tx.Error
	return
}
func (d clientDao) Create(m *tables.AmsClient) (err error) {
	err = DB.Create(m).Error
	if err != nil {
		return err
	}
	Cache.SetClient(*m)
	return nil
}

func (d clientDao) Update(m tables.AmsClient) (err error) {
	err = DB.Updates(&m).Error
	if err != nil {
		return err
	}
	Cache.SetClient(m)
	return nil
}

func (d clientDao) FindById(id int64) (m tables.AmsClient, err error) {
	err = DB.Where("id = ?", id).Find(&m).Error
	return
}

func (d clientDao) FindByIds(ids []int64) (li []tables.AmsClient, err error) {
	err = DB.Where("id in ?", ids).Find(&li).Error
	return
}

func (d clientDao) FindByUniqueCode(ucode string) (m tables.AmsClient, err error) {
	err = DB.Where("unique_code = ?", ucode).Find(&m).Error
	return
}

func (d clientDao) FindAbnormalByUniqueCode(ucode string) (m tables.AmsClientAbnormal, err error) {
	err = DB.Where("unique_for_file = ?", ucode).Find(&m).Error
	return
}

func (d clientDao) CreateAbnormal(m *tables.AmsClientAbnormal) (err error) {
	m.CreatedAt = time.Now().Unix()
	err = DB.Create(m).Error
	return
}

func (d clientDao) UpdateAbnormal(m tables.AmsClientAbnormal) (err error) {
	m.UpdatedAt = time.Now().Unix()
	err = DB.Save(&m).Error
	return
}
